package org.shangda.wechat.pet.web.controller.miniapp;

import org.shangda.wechat.pet.config.BaseProperties;
import org.shangda.wechat.pet.enums.ErrorCode;
import org.shangda.wechat.pet.error.BussinessException;
import org.shangda.wechat.pet.util.Constants;
import org.shangda.wechat.pet.util.FileUtil;
import com.ijpay.core.kit.WxPayKit;
import com.power.common.model.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 小程序文件上传
 */
@Slf4j
@RestController
@RequestMapping("miniapp/")
public class MiniappUploadController {

    @Resource
    private BaseProperties baseProperties;

    /**
     * 上传游记文件
     * @param file
     * @return
     */
    @RequestMapping(value="/upload_tourist_image", method = RequestMethod.POST)
    public CommonResult uploadTouristImage(@RequestParam("file") MultipartFile file) {
        try {
            if (file == null || file.getSize() > 30 * 1024 * 1024) { //文件大小不超过30M
                log.error("upload_tourist_image 文件对象为空或文件太大，请更换文件");
                throw new BussinessException(ErrorCode.FILE_OUT_MAX_SIZE);
            }

            String fileName = file.getOriginalFilename();
            log.info("upload_tourist_image fileName : {}, fileSize : {}", fileName, file.getBytes().length);
            String suffix = fileName.substring(fileName.lastIndexOf("."));

            String baseUploadDir = baseProperties.getUploadImageBasePath() + Constants.TOURIST_NOTE_IMAGE_DIR + "/";
            String destName =  WxPayKit.generateStr() + suffix;
            log.info("upload_tourist_image baseUploadDir : {} , destName : {}", baseUploadDir, destName);
            FileUtil.uploadFile(file.getBytes(), baseUploadDir, destName);
            String imageUrl = baseProperties.getImageBaseUrl() + Constants.TOURIST_NOTE_IMAGE_DIR + "/" + destName;
            return CommonResult.ok().setResult(imageUrl);
        } catch (Exception e) {
            log.error("upload file transfer error!", e);
        }
        return CommonResult.fail();
    }

}
